package com.ruoyi.web.hb.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.web.hb.domain.ChannelBuoy;
import com.ruoyi.web.hb.domain.ChannelBuoyInfos;
import com.ruoyi.web.hb.mapper.ChannelBuoyMapper;
import com.ruoyi.web.hb.service.IChannelBuoyService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 航标基础数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-19
 */
@Service
public class ChannelBuoyServiceImpl implements IChannelBuoyService {
    @Autowired
    private ChannelBuoyMapper channelBuoyMapper;

    @Autowired
    private RedisCache redisCache;

    private Logger log = LoggerFactory.getLogger(ChannelBuoyServiceImpl.class);

    /**
     * 查询航标基础数据
     *
     * @param id 航标基础数据主键
     * @return 航标基础数据
     */
    @Override
    public ChannelBuoy selectChannelBuoyById(Long id) {
        return channelBuoyMapper.selectChannelBuoyById(id);
    }

    @Override
    public List<Map> selectChannelBuoyCount() {
        return channelBuoyMapper.selectChannelBuoyCount();
    }

    /**
     * 查询航标基础数据列表
     *
     * @param channelBuoy 航标基础数据
     * @return 航标基础数据
     */
    @Override
    public List<ChannelBuoy> selectChannelBuoyList(ChannelBuoy channelBuoy) {
        return channelBuoyMapper.selectChannelBuoyList(channelBuoy);
    }

    @Override
    public ChannelBuoyInfos selectChannelBuoyInfo(ChannelBuoy channelBuoy) {
        return channelBuoyMapper.selectChannelBuoyInfo(channelBuoy);
    }

    /**
     * 新增航标基础数据
     *
     * @param channelBuoy 航标基础数据
     * @return 结果
     */
    @Override
    public int insertChannelBuoy(ChannelBuoy channelBuoy) {
        channelBuoy.setCreateTime(DateUtils.getNowDate());
        return channelBuoyMapper.insertChannelBuoy(channelBuoy);
    }

    /**
     * 修改航标基础数据
     *
     * @param channelBuoy 航标基础数据
     * @return 结果
     */
    @Override
    public int updateChannelBuoy(ChannelBuoy channelBuoy) {
        channelBuoy.setUpdateTime(DateUtils.getNowDate());
        return channelBuoyMapper.updateChannelBuoy(channelBuoy);
    }

    /**
     * 批量删除航标基础数据
     *
     * @param ids 需要删除的航标基础数据主键
     * @return 结果
     */
    @Override
    public int deleteChannelBuoyByIds(Long[] ids) {
        return channelBuoyMapper.deleteChannelBuoyByIds(ids);
    }

    /**
     * 删除航标基础数据信息
     *
     * @param id 航标基础数据主键
     * @return 结果
     */
    @Override
    public int deleteChannelBuoyById(Long id) {
        return channelBuoyMapper.deleteChannelBuoyById(id);
    }

    @Override
    public String getNavigationToken() throws IOException {

        String url = "http://10.22.4.86:8170/smartyh/conservation-service/conservation/api/getToken";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        HttpEntity entity = MultipartEntityBuilder.create()
                .addTextBody("appId", "decff5f48faf18a163b47d3c88d15659")
                .addTextBody("appSecret", "1blvbjztyzdpxjmn41gk0703uzy84rnbsmrem6ds9ejpdl89qetvlwwa2j69xrh9")
                .build();
        // 设置请求实体
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        //是否请求成功
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //返回json格式
            String res = EntityUtils.toString(response.getEntity());
            Map result = JSON.parseObject(res);
            if (result.get("code").equals("0000")) {//成功
                Map data = (Map) result.get("data");
                String string = data.get("token").toString();
                //获取航标token存到redis
                redisCache.setCacheObject("navigationToken", string, 3300, TimeUnit.SECONDS);
                log.info("获取航标token成功{}", string);
                return string;
            } else {
                String message = result.get("message").toString();
                log.info("获取航标token失败{}", message);
                throw new RuntimeException("获取航标token失败"+message);
            }
        }
        return "访问接口失败";
    }

    @Override
    public List<Map> getNavigationList() throws IOException {
        String navigationToken;
        if (!redisCache.hasKey("navigationToken")) {
             getNavigationToken();
        }
        navigationToken = redisCache.getCacheObject("navigationToken").toString();
        String url = "http://10.22.4.86:8170/smartyh/conservation-service/conservation/api/getSubeiHbList?token="+ navigationToken + "&organId=00020021";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);

        HttpResponse response = httpClient.execute(get);
        //是否请求成功
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //返回json格式
            String res = EntityUtils.toString(response.getEntity());
            Map result = JSON.parseObject(res);
            if (result.get("code").equals("0000")) {//成功
                List<Map> data = (List<Map>) result.get("data");
                log.info("获取航标数据成功,共{}条",data.size());
                return data;
            } else {
                String message = result.get("message").toString();
                log.info("获取航标数据失败", message);
                throw new RuntimeException("获取航标数据失败"+message);
            }
        }
        return null;
    }
}
